﻿<?php
// 签名公司效验地址 https://mp.weixin.qq.com/debug/cgi-bin/sandbox?t=jsapisign
// 方法1 get_access_token() 获取 access_token
// 方法2 get_jsapi_ticket() 获取 jsapi_ticket
// 方法3 fen_xaing_config($url) 获取js分享配置文件,需要传入分享的地址(#号以前的)
class WeiXingInit
{

    public $APPID = 'wxb0865099ce398fa2';
    public $SECRET = '04061da105838ef835c8d403592db7cf';
    public $CORPID = 'wwdc02ce3b575253e3';
    public $CORPSECRET = 'dQGDFOP6AieB4PzMAN6x6_16cDC1bGUhAMj_88i9_7s';

    // access_token 存储文件 频繁刷新access_token会导致api调用受限，影响自身业务，开发者必须在自己的服务全局缓存access_token
    public $fileName_access = 'access_token';
    // jsapi_ticket 存储文件 频繁刷新jsapi_ticket会导致api调用受限，影响自身业务，开发者必须在自己的服务全局缓存jsapi_ticket
    public $fileName_jsapi_ticket = 'jsapi_ticket';

    public $debug = false;

    // 获取 access_token
    public function get_access_token()
    {
        $data = [];

        if (is_file($this->fileName_access)) {

            // 验证是否过期
            $time = time();
            $data = json_decode(file_get_contents($this->fileName_access), true);

            if (($time - $data['time']) > ($data['expires_in'] - 100)) {
                $data = $this->access_token_get_save();
            }
        } else {
            $data = $this->access_token_get_save();
        }

        //print_r($data);

        return $data;
    }

    // access_token 获取保存
    public function access_token_get_save()
    {
        // $url = "https://api.weixin.qq.com/cgi-bin/token";
        // $post_string = "grant_type=client_credential&appid=" . $this->APPID . "&secret=" . $this->SECRET;

        $url = "https://qyapi.weixin.qq.com/cgi-bin/gettoken";
        $post_string = "corpid=" . $this->CORPID . "&corpsecret=" . $this->CORPSECRET;

        // $post_string = array(
        //     'grant_type' => 'client_credential',
        //     'appid' => $this->APPID,
        //     'secret' => $this->SECRET
        // );

        $url = $url . '?' . $post_string;

        //echo  "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=$this->APPID&secret=$this->SECRET".'<br/>';

        // print_r($post_string);
        // $this->curl($url);exit;
        $data = json_decode($this->curl($url), true);
        $data['time'] = time();
        file_put_contents($this->fileName_access, json_encode($data));
        return $data;
    }

    // 获取 jsapi_ticket
    public function get_jsapi_ticket()
    {
        $data = [];

        if (is_file($this->fileName_jsapi_ticket)) {

            // 验证是否过期
            $time = time();
            $data = json_decode(file_get_contents($this->fileName_jsapi_ticket), true);

            if (($time - $data['time']) > ($data['expires_in'] - 100)) {
                $data = $this->jsapi_ticket_get_save();
            }
        } else {
            $data = $this->jsapi_ticket_get_save();
        }

        return $data;
    }

    // jsapi_ticket 获取保存
    public function jsapi_ticket_get_save()
    {
        $data = [];

        $data_access = $this->get_access_token();

        if (!empty($data_access['access_token'])) {
            // $url = "https://api.weixin.qq.com/cgi-bin/ticket/getticket";
            // $post_string = "access_token=" . $data_access['access_token'] . "&type=jsapi";

            $url = "https://qyapi.weixin.qq.com/cgi-bin/get_jsapi_ticket";
            $post_string = "access_token=" . $data_access['access_token'];

            // $url = "https://qyapi.weixin.qq.com/cgi-bin/ticket/get";
            // $post_string = "access_token=" . $data_access['access_token'] . "&type=agent_config";

            $url = $url . '?' . $post_string;

            //echo "https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token=$data_access&type=jsapi";
            //echo '<pre>';
            //echo $url;
            //echo '</pre>';
            $data = json_decode($this->curl($url, $post_string), true);
            //print_r($data);
            $data['time'] = time();
            file_put_contents($this->fileName_jsapi_ticket, json_encode($data));
        }
        return $data;
    }

    // 生成随机字符串
    public function generate_password($length = 8)
    {
        // 密码字符集，可任意添加你需要的字符
        $chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
        $password = "";
        for ($i = 0; $i < $length; $i++) {
            // 这里提供两种字符获取方式
            // 第一种是使用 substr 截取$chars中的任意一位字符；
            // 第二种是取字符数组 $chars 的任意元素
            // $password .= substr($chars, mt_rand(0, strlen($chars) – 1), 1);
            $password .= $chars[mt_rand(0, strlen($chars) - 1)];
        }
        return $password;
    }

    // 微信分享config
    public function fen_xaing_config($url)
    {
        $noncestr = $this->generate_password(15);
        $time = time();
        return [
            'debug' => $this->debug,
            'appId' => $this->CORPID, // 必填，公众号的唯一标识
            'timestamp' => $time, // 必填，生成签名的时间戳
            'nonceStr' => $noncestr, // 必填，生成签名的随机串
            'signature' => $this->get_qian_ming($url, $time, $noncestr), // 必填，签名
            'jsApiList' => ['onMenuShareTimeline', 'onMenuShareAppMessage', 'onMenuShareQQ', 'onMenuShareWeibo', 'onMenuShareQZone'], // 必填，需要使用的JS接口列表
        ];
    }

    // 生成签名
    public function get_qian_ming($url, $t_time, $noncestr)
    {
        // echo '<pre>';
        // echo $url,$time,$noncestr;
        // echo '</pre>';
        $data_jsapi = $this->get_jsapi_ticket();

        // echo '<pre>';
        // print_r($data_jsapi);
        // echo '</pre>';
        $str = "";
        if (!empty($data_jsapi['ticket'])) {
            $jsapi_ticket = $data_jsapi['ticket'];
            $timestamp = $t_time;
            // echo '<br/>';
            // echo $jsapi_ticket;
            // echo '<br/>';
            // $str = 'jsapi_ticket='.$jsapi_ticket.'&noncestr='.$noncestr.'&amp;timestamp='.$timestamp.'&url='.$url;
            $str = 'jsapi_ticket=' . $jsapi_ticket . '&noncestr=' . $noncestr . '&timestamp=' . $timestamp . '&url=' . $url;
            // $str = 'jsapi_ticket=kgt8ON7yVITDhtdwci0qefCt8TqW2UbvbGmqj1PymKN103FLvN7EJumA2AJ7FuhJBSCt9UqP49Ta1t6WJ7-BKA&noncestr=TSRNqDBWuTkKOWj&timestamp=1539914956&url=http://manggement.inforward.com.cn';
            // echo $str.'<br/>';
            $str = sha1($str);
        }
        return $str;

    }

    public function curl($url, $post_string = '')
    {

        $curl = curl_init();
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($curl, CURLOPT_TIMEOUT, 500);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
        curl_setopt($curl, CURLOPT_URL, $url);
        $res = curl_exec($curl);
        curl_close($curl);
        return $res;

        // $ch = curl_init();
        // curl_setopt($ch, CURLOPT_URL, $remote_server);
        // curl_setopt($ch, CURLOPT_POSTFIELDS,$post_string);
        // curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        // // curl_setopt($ch, CURLOPT_USERAGENT, "qianyunlai.com's CURL Example beta");
        // $data = curl_exec($ch);
        // print_r($data);
        // curl_close($ch);
        // return $data;

        $ch = curl_init();
        curl_setopt($ch, CURLOPT_TIMEOUT, 15);
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); //如果接口URL是https的,我们将其设为不验证,如果不是https的接口,这句可以不用加
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
        if (!empty($data)) {
            curl_setopt($ch, CURLOPT_POST, 1);
            curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
        }
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        $output = curl_exec($ch);
        if ($output) {
            curl_close($ch);
            return $output;
        } else {
            $this->err = curl_errno($ch);
            curl_close($ch);
            return $this->err;
        }

    }

}

$weiXingInit = new WeiXingInit();
$url = $_GET['url'];
// print_r($url);exit;
// print_r($url['url']);exit;

// $info = $weiXingInit->fen_xaing_config($url['url']);
$info = $weiXingInit->fen_xaing_config($url);

// $info = $weiXingInit->fen_xaing_config('http://web.inforward.com.cn');
header('Access-Control-Allow-Origin:*'); //支持全域名访问，不安全，部署后需要固定限制为客户端网址
header('Access-Control-Allow-Methods:POST,GET,OPTIONS,DELETE'); //支持的http 动作
header('Access-Control-Allow-Headers:x-requested-with,content-type'); //响应头 请按照自己需求添加。
$result = array('code' => 1, 'msg' => '查询成功', 'data' => $info, 'url' => '', 'wait' => '');
// print_r($result);
// echo $url;exit;
echo json_encode($result);exit;

echo '<pre>';
print_r($result);
echo '</pre>';
?></code>
